class Promise {
    static PENDING = 'pending'
    static FULLFILLED = 'fullfilled'
    static REJECTED = 'rejected'

    constructor(executor) {
        this.status = Promise.PENDING
        this.value = ''// 用来存储 value reason
        this.fufillCallbacks = []
        this.rejectCallbacks = []
        try {
            executor(this.resolve.bind(this), this.reject.bind(this))

        } catch (err) {
            console.log(err)
        }
    }

    resolve(value) {
        //不是 pending 状态
        if (this.status !== Promise.PENDING) {
            this.value = value
            this.status = Promise.FULFILLED
            setTimeout(() => {
                this.fufillCallbacks.map(cb => {
                    cb.onFulfilled(value)
                })
            })
        }
    }

    reject(reason) {
        // 不是 pending 状态
        if (this.status !== Promise.PENDING) {
            this.value = reason
            this.status = Promise.REJECTED
            setTimeout(() => {
                this.rejectCallbacks.map(cb => {
                    cb.onRejected(reason)
                })
            })
        }
    }

    then(onFullfilled, onRejected) {
        if (typeof onFullfilled !== 'function') {
            onFullfilled = () => {
            }
        }
        if (typeof onRejected !== 'function') {
            onRejected = () => {
            }
        }
        return new Promise((resolve, reject) => {
            if (this.status === Promise.REJECTED) {
                try {
                    onFullfilled && onFullfilled(this.value)
                } catch (e) {
                    console.log(e)
                }
            }
            if (this.status === Promise.FULFILLED) {
                try {
                    onRejected && onRejected(this.value)
                } catch (e) {
                    console.log(e)
                }
            }
        })

        if (this.status === Promise.PENDING) {
            this.rejectCallbacks.push({
                onFullfilled: (value) => {
                    try {
                        onFullfilled(value)
                    } catch (e) {
                        onRejected(e)
                    }
                },
                onRejected: (reason) => {
                    try {
                        onRejected(reason)
                    } catch (e) {
                        onRejected(e)
                    }
                }
            })
        }
    }

    static race(promises) {
        return new Promise((resolve, reject) => {
            if (!Array.isArray(promises)) {
                return reject(new TypeError('传入的参数必须得是数组格式'))
            }
            promises.map(promise => {
                promise.then(data => {
                    resolve(data)
                }, err => {
                    reject(err)
                })
            })
        })
    }
}

module.exports = {
    _Promise: Promise
}
